package com.iptv.grape;

import android.app.Activity;
import android.app.Application;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.bu.GrapeInitBack;
import com.iptv.grape.domain.UserInfo;
import com.iptv.grape.event.EventArgs;
import com.iptv.grape.net.Entity.LoginData;
import com.iptv.grape.net.Entity.LoginResult;
import com.iptv.grape.net.NetworkService;
import com.iptv.grape.ui.dlg.DlgMgr;
import com.iptv.grape.util.ActMgr;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ReadJsonFile;
import com.iptv.grape.util.SharedUtil;
import com.iptv.grape.video.XMediaPlayer;
import com.tencent.smtt.sdk.QbSdk;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class RunTimeApplication extends Application implements GrapeInitBack, Application.ActivityLifecycleCallbacks {

    private static final String VALUE = "Harvey";
    private static RunTimeApplication curApp = null;

    private boolean isDebug = true;
    private boolean isLogin = false;

    private int deviceHeigth;

    public GrapeContext getGrapeContext() {
        return GrapeContext.curGrapeContext();
    }

    private int devicewidth;

    public int getDeviceHeigth() {
        return deviceHeigth;
    }

    public int getDevicewidth() {
        return devicewidth;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(this);
        curApp = this;
        GrapeContext.curGrapeContext().setGrapeInitBack(this);
        EventBus.getDefault().register(this);
        //NetworkService.getInstance().login();
        //AppLog.getCurLog().out("App----login");

        DisplayMetrics dm = new DisplayMetrics();
        deviceHeigth = dm.heightPixels;
        devicewidth = dm.widthPixels;

        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                //Log.d("app", " onViewInitFinished is " + arg0);
                AppLog.getCurLog().out("onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);

    }


    public static RunTimeApplication getCurApp() {
        return curApp;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(EventArgs eventArgs) {
//
//        if(eventArgs.getEventName().equals("login")) {
//
//            if( eventArgs.getIsExistsArgs()){
//                LoginResult result = (LoginResult)eventArgs.getEventArgs();
//                AppLog.getCurLog().out("result.getRtCode()" + result.getRtCode());
//                if(result.getRtCode().equals("S")){
//                    // 登录成功
//                    LoginData data = result.getData();
//                    UserInfo.setLoginInfo(data);
//                    this.isLogin = true;
//                    AppLog.getCurLog().out(this.isLogin);
//                }
//                else{
//                    // 登录失败
//                    AppLog.getCurLog().out("result.getReason() = " +  result.getReason());
//                }
//            }
//            else {
//                // 访问异常
//            }
//        }


    }

    // 是否登录
    public boolean isLogin() {
        return isLogin;
    }

    // isDebug
    public boolean isDebug() {
        return isDebug;
    }

    @Override
    public void initDlg(int type, String msg) {
        Activity activity = ActMgr.istc().getCurrentActivity();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DlgMgr.grapeInitDlg(activity, msg);
            }
        });

    }

    private Handler auth = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            long time = SharedUtil.getSp(SharedUtil.FILE_DEFUALT).getLong("auth_time", 0L);
            long curTime = (System.currentTimeMillis() / 1000);
            if (time != 0L && curTime - time >= 1 * 60) {
                Activity activity = ActMgr.istc().getCurrentActivity();
                AppLog.getCurLog().e("11=====>>",activity.getClass().getSimpleName());
                auth(activity);
            } else {
                auth.postDelayed(this, 5000);
            }
        }
    };

    @Override
    public void goOnAuth(int type) {
        switch (type) {
            case GrapeInitBack.AUTH_301:
                auth.postDelayed(runnable, 5000);
                break;
            case GrapeInitBack.AUTH_305:
                auth.postDelayed(runnable, 5000);
                break;
            case GrapeInitBack.AUTH_SUCCESS:
                auth.postDelayed(runnable, 5000);

                break;
        }
    }


    private void auth(Activity act) {
        NetworkService.getInstance().login(new NetworkService.OkCall() {
            @Override
            public void error(int code, String msg) {

                showDlg(act, getString(R.string.dlg_auth_noresponse));

            }

            @Override
            public void success(String value) {
                try {
                    LoginResult loginResult = LoginResult.CreateForJson(value);
                    if (loginResult.getRtCode().equals("S")) {
                        // 认证成功
                        UserInfo.setLoginInfo(loginResult.getData());
                        // 设置定时器 下次在继续认证
                        SharedUtil.put(SharedUtil.FILE_DEFUALT, "auth_time", (System.currentTimeMillis() / 1000));
                        auth.postDelayed(runnable, 5000);
                        return;
                    } else if (loginResult.getRtCode().equals("F")) {
                        // 明确了错误 停机 或者 销户 或者错误的状态 通知MainAct弹出对话框 显示出失败原因
                        String reason = loginResult.getReason();
                        switch (reason) {
                            case "UserDowntime":
                                showDlg(act, "您的账户已停机");
                                break;
                            case "UserAccountCancellation":
                                showDlg(act, "您的账户已销户");
                                break;
                            case "UserStatusError":
                                showDlg(act, "用户状态异常 数据错误或者程序BUG 需要联系厂家");
                                break;
                        }
                        UserInfo.setLoginInfo(loginResult.getData());
                        return;
                    }
                } catch (Exception e) {

                    showDlg(act, getString(R.string.dlg_login_null));
                }
            }
        });
    }


    private void showDlg(Activity act, String value) {
        act.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                DlgMgr.grapeInitDlg(act, value);
                XMediaPlayer xMediaPlayer = GrapeContext.curGrapeContext().getCurMediaPlayer();
                if(xMediaPlayer!=null&&xMediaPlayer.isPlaying()){
                    xMediaPlayer.stop();
                }
            }
        });

    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        AppLog.getCurLog().e("11=====>>",activity.getClass().getSimpleName());
        ActMgr.istc().setCurrentActivity(activity);
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }

    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        super.onTerminate();
        if(auth!=null){
            auth.removeCallbacks(runnable);
            auth.removeCallbacksAndMessages(null);
        }
        auth = null;
    }
    @Override
    public void onLowMemory() {
        // 低内存的时候执行
        super.onLowMemory();
    }
    @Override
    public void onTrimMemory(int level) {
        // 程序在内存清理的时候执行
        super.onTrimMemory(level);
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}
